<template>
  <div v-loading="loading" class="rc-cont">
    <div v-if="!isSeas" class="rc-head">
      <el-button icon="el-icon-plus" @click="addFile">
        {{ $t('crm.components.09d4fb94cc99531f0ab2533a0e652e9c') }}
      </el-button>
      <input
        ref="fileInput"
        type="file"
        class="rc-head-file"
        accept="*/*"
        multiple
        @change="uploadFile" />
    </div>
    <el-table
      :data="list"
      :height="tableHeight"
      class="file-table"
      stripe
      @row-click="handleRowClick">
      <el-table-column
        v-for="(item, index) in fieldList"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        show-overflow-tooltip>
        <template slot-scope="{ row, column }">
          <wx-open-data
            v-if="column.property === 'createUserName'"
            :openid="row.createUserName" />
          <template v-else>{{ row[column.property] }}</template>
        </template>
      </el-table-column>
      <el-table-column
        prop="audio"
        label="音频播放"
        width="300px">
        <template slot-scope="{ row }">
          <audios
            v-if="isAudios(row.name)"
            :props="getAudiosProps(row)" />
        </template>
      </el-table-column>
      <el-table-column
      :label="$t('crm.components.8043e151bd60d326d4ee0c3472ddc2bd')"
        width="200">
        <template slot-scope="scope">
          <el-button
            type="primary-text"
            style="padding: 0;"
            @click.native="handleFile('preview', scope)">
            {{ $t('crm.components.1e204b32548f5f0431d436774ccf19f2') }}
          </el-button>
          <el-button
            type="primary-text"
            style="padding: 0;"
            @click.native="handleFile('download', scope)">
            {{ $t('crm.components.cf8448d7238b13bcacacfce515e71772') }}
          </el-button>
          <el-button
            :disabled="scope.row.readOnly == 1"
            type="primary-text"
            style="padding: 0;"
            @click.native="handleFile('edit', scope)">
            {{ $t('crm.components.905c0a4fb5432dbe3522b77efb488450') }}
          </el-button>
          <el-button
            :disabled="scope.row.readOnly == 1"
            type="primary-text"
            style="padding: 0;"
            @click.native="handleFile('delete', scope)">
            {{ $t('crm.components.5c264c878c1df450903b2b97c3bf3c6c') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :append-to-body="true"
      :close-on-click-modal="false"
      :visible.sync="editDialog"
      :title="$t('crm.components.85bb6c5a20e3d154b6fe2b0facaf52b3')"
      width="30%">
      <el-form :model="editForm">
        <el-form-item
          :label="$t('crm.components.3cddda41cdfe98e62ee332ed2248568c')"
          label-width="100">
          <el-input v-model="editForm.name" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmEdit">
          {{ $t('crm.components.a5279f1b56de336d512d10213f7feb03') }}
        </el-button>
        <el-button @click="editDialog = false">
          {{ $t('crm.components.6be2bb33a57370b9499140790978d86a') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script type="text/javascript">
import { crmFileDeleteAPI, crmFileUpdateAPI, downloadFileAPI } from '@/api/common'

import { crmLeadsFileListAPI } from '@/api/crm/leads'
import { crmCustomerFileListAPI } from '@/api/crm/customer'
import { crmContactsFileListAPI } from '@/api/crm/contacts'
import { crmBusinessFileListAPI } from '@/api/crm/business'
import { crmContractFileListAPI } from '@/api/crm/contract'
import { crmProductFileListAPI } from '@/api/crm/product'
import { crmReceivablesFileListAPI } from '@/api/crm/receivables'
import { crmReceivablesPlanFileListAPI } from '@/api/crm/receivablesPlan'
import { crmReturnVisitFileAPI } from '@/api/crm/visit'
import { crmInvoiceFileListAPI } from '@/api/crm/invoice'

import Audios from '@/components/Audios'

import { fileSize, canPreviewFile, wkPreviewFile, downloadFileWithBuffer } from '@/utils'
import { debounce } from 'throttle-debounce'

export default {
  name: 'RelativeFiles', // 相关附件  可能再很多地方展示 放到客户管理目录下
  components: {
    Audios
  },
  inject: ['rootTabs'],
  props: {
    /** 模块ID */
    id: [String, Number],
    /** 联系人人下 新建商机 需要联系人里的客户信息  合同下需要客户和商机信息 */
    detail: {
      type: Object,
      default: () => {
        return {}
      }
    },
    /** 没有值就是全部类型 有值就是当个类型 */
    crmType: {
      type: String,
      default: ''
    },
    /** 是公海 默认是客户 */
    isSeas: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      list: [],
      fieldList: [],
      tableHeight: '400px',
      /** 重命名 弹窗 */
      editDialog: false,
      /** 编辑信息 */
      editForm: { name: '', data: {}}
    }
  },
  computed: {},
  watch: {
    id(val) {
      this.list = []
      this.getDetail()
    },

    'rootTabs.currentName'(val) {
      if (val === 'RelativeFiles') {
        this.getDetail(false)
      }
    }
  },
  mounted() {
    this.fieldList.push({ prop: 'name', width: '200', label: this.$t('crm.components.e188bef4c23a27f07e6d44bcfb56cdef') })
    this.fieldList.push({ prop: 'size', width: '100', label: this.$t('crm.components.8fdfec846e7e6330506090f48bc0453e') })
    this.fieldList.push({
      prop: 'createUserName',
      width: '100',
      label: this.$t('crm.components.1278fa3af12e06d17d988027675782d8')
    })
    this.fieldList.push({
      prop: 'createTime',
      width: '200',
      label: this.$t('crm.components.0a9342387bdcd5011c155faef2fbfd06')
    })
    this.fieldList.push({ prop: 'source', width: '100', label: this.$t('crm.components.da3a817bc4f264d6a3d91aa81625f2ef') })
    this.getDetail()

    this.debouncedGetDetail = debounce(300, () => {
      this.$bus.emit('crm-tab-num-update')
      this.getDetail()
    })
  },
  methods: {
    getDetail(loading = true) {
      this.loading = loading
      const request = {
        leads: crmLeadsFileListAPI,
        customer: crmCustomerFileListAPI,
        contacts: crmContactsFileListAPI,
        business: crmBusinessFileListAPI,
        contract: crmContractFileListAPI,
        product: crmProductFileListAPI,
        receivables: crmReceivablesFileListAPI,
        receivablesPlan: crmReceivablesPlanFileListAPI,
        visit: crmReturnVisitFileAPI,
        invoice: crmInvoiceFileListAPI
      }[this.crmType]
      const params = {}
      params['id'] = this.id
      request(params)
        .then(res => {
          this.loading = false
          this.list = res.data.map(item => {
            item.size = fileSize(item.size)
            return item
          })
        })
        .catch(() => {
          this.loading = false
        })
    },
    addFile() {
      this.$refs.fileInput.click()
    },
    /** 图片选择出发 */
    uploadFile(event) {
      var files = event.target.files
      for (let index = 0; index < files.length; index++) {
        const file = files[index]
        var params = {}
        params.batchId = this.detail.batchId
        params.file = file
        this.$wkUploadFile.upload({
          file: file,
          params: {
            batchId: this.detail.batchId
          }
        }).then(completeData => {
          this.debouncedGetDetail()
        }).catch(() => {})
      }

      event.target.value = ''
    },
    // 当某一行被点击时会触发该事件
    handleRowClick(row, column, event) {},

    showPreviewBtn(item) {
      return canPreviewFile(item.row.name)
    },

    /**
     * @description: 获取录音文件的配置
     * @param {*}
     * @return {*}
     */
    getAudiosProps(item) {
      return {
        fileRequest: downloadFileAPI, // 添加请求和参数
        fileParams: item.url
      }
    },

    /**
     * 编辑删除cell
     */
    handleFile(type, item) {
      if (type === 'preview') {
        if (canPreviewFile(item.row.name)) {
          wkPreviewFile(item.row.url, item.row.name)
        } else {
          this.$wkPreviewFile.preview({
            index: item.$index,
            data: this.list
          })
        }
      } else if (type === 'delete') {
        this.$confirm(
          this.$t('crm.components.6c3218b8c5812e0c451d88cda755b95a'),
          this.$t('crm.components.9b98f0ccb9410a4e5deb56cb7b61a582'),
          {
            confirmButtonText: this.$t('crm.components.2c7f2829a725b4b48701641ca1ca09e7'),
            cancelButtonText: this.$t('crm.components.b466f62e5c67e3cf7393e1b25318beb2'),
            type: 'warning'
          }
        )
          .then(() => {
            crmFileDeleteAPI({
              id: item.row.fileId
            })
              .then(res => {
                this.list.splice(item.$index, 1)
                this.$bus.emit('crm-tab-num-update')
                this.$message.success(this.$t('crm.components.5b5a647e077d27ffe375aaf03cda864c'))
              })
              .catch(() => {})
          })
          .catch(() => {})
      } else if (type === 'download') {
        downloadFileAPI(item.row.url).then(res => {
          downloadFileWithBuffer(res.data, item.row.name)
        }).catch(() => {})
      } else {
        this.editForm.data = item
        this.editForm.name = item.row.name
        this.editDialog = true
      }
    },

    confirmEdit() {
      if (this.editForm.name) {
        crmFileUpdateAPI({
          fileId: this.editForm.data.row.fileId,
          name: this.editForm.name
        })
          .then(res => {
            this.$message.success(this.$t('crm.components.69f7d5b2d4889d2e0151b4cc7589aef3'))
            this.editDialog = false
            var item = this.list[this.editForm.data.$index]
            item.name = this.editForm.name
          })
          .catch(() => {})
      }
    },

    /**
     * @description: 根据名称内是否包含mp3 或者 wav 判断是否因为
     * @param {*} name
     * @return {*}
     */
    isAudios(name) {
      if (name) {
        const lowerName = name.toLowerCase()
        return lowerName.includes('mp3') || lowerName.includes('wav')
      }
      return false
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../styles/relativecrm.scss";

.h-item {
  margin: 0 5px;
  font-size: 13px;
  color: #409eff;
  cursor: pointer;
}

.rc-head-file {
  position: absolute;
  top: 0;
  right: 0;
  z-index: -1;
  width: 98px;
  height: 98px;
  cursor: pointer;
  opacity: 0;
}
</style>
